package com.whitehot.wsdemo;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.google.gson.Gson;
import com.neovisionaries.ws.client.WebSocket;
import com.neovisionaries.ws.client.WebSocketException;
import com.neovisionaries.ws.client.WebSocketFrame;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity
{

    public static final String CLIENT_ST_MD = "0-c";
    public static final String CLIENT_ED_MD = "1-c";

    public static final String CLIENT_ST_MD_RESP = "0-c-sc";
    public static final String CLIENT_ED_MD_RESP = "1-c-sc";

    CameraManager cameraManager;
    private Vibrator vibrator;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        manager = WsManager.getInstance();
        vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
        req();
    }

    private void req()
    {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED)
        {

            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 0);
        }else
        {
            cameraManager = (CameraManager) getSystemService(CAMERA_SERVICE);
            try {
                String [] camerList = cameraManager.getCameraIdList();
                for (String str:camerList) {
                    Log.d("List",str);
                }
            } catch (CameraAccessException e) {
                Log.e("error",e.getMessage());
            }
        }
    }


    WsManager manager;

    public void click(View view)
    {
        if (manager.isClosed())
        {
            manager.init();
            manager.setListener(new WsManager.Listener()
            {
                @Override
                public void onConnected(WebSocket websocket, Map<String, List<String>> headers)
                {
                    manager.sendText(CLIENT_ST_MD);
                }

                @Override
                public void onConnectError(WebSocket websocket, WebSocketException exception)
                {

                }

                @Override
                public void onTextMessage(WebSocket websocket, String text)
                {
                    Log.e("s", "server: " + text);
                    if (CLIENT_ST_MD_RESP.equals(text))
                    {
                        Gson g = new Gson();
                        WsResp r = new WsResp();
                        r.type = 0;
                        WsClientBean bean = new WsClientBean();
                        bean.token = "Absd89712hkfhskdf==";
                        bean.device = Build.BRAND;
                        bean.userName = "ytf";
                        bean.logTime = sdf.format(new Date(System.currentTimeMillis()));
                        r.data = bean;
                        String s = g.toJson(r);
                        Log.e("s", "info->" + s);
                        manager.sendText(s);
                    }
                    if ("cli-0".equals(text))
                    {
                        Log.e("s", "进来了");
                        if(isOnOperating)
                            return;
                        if(!isOpened)
                        {
                            isOnOperating = true;
                            Log.e("s", "准备");
                            openLight();
                        }else
                        {
                            isOnOperating = true;
                            closeLight();
                        }
                        isOnOperating = false;
                        isOpened = !isOpened;
                    }
                }

                @Override
                public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer)
                {

                }
            });
        }
    }

    boolean isOpened;
    boolean isOnOperating;

    private void openLight()
    {
        runOnUiThread(new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    long [] pattern = {100,300,100,300};
                    vibrator.vibrate(pattern,1);
                    Toast.makeText(MainActivity.this, "jjj", Toast.LENGTH_SHORT).show();
                } catch (Exception ex)
                {
                }
            }
        });
    }

    private void closeLight()
    {
        runOnUiThread(new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    if(vibrator != null)
                        vibrator.cancel();
                    Toast.makeText(MainActivity.this, "sss", Toast.LENGTH_SHORT).show();
                } catch (Exception ex)
                {
                }
            }
        });

    }

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    protected void onDestroy()
    {
        WsManager.getInstance().disconnect();
        if (isOpened)
        {
            closeLight();
        }
        super.onDestroy();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
    {
        if(grantResults[0] == PackageManager.PERMISSION_GRANTED && requestCode == 0)
        {
            cameraManager = (CameraManager) getSystemService(CAMERA_SERVICE);
        }
    }
}
